/*
 * EK.Rewriter
 * Inspired by Apache mod_rewrite
 * 
 * Enrichment Kit @ek.version@ (http://enrichmentkit.com)
 * Copyright (c) 2008 Pink Hominid
 * Licensed under terms of the MIT License (LICENSE.txt)
 * 
 * IE 6.0+, FF 1.5+ Tested
 */

/**
 * Manipulates URLs using regex rules.
 * @constructor
 */
EK.Rewriter = function EkRewriter() {
    
    /**
     * Set of named rewrite rules. Rules evaluated in defined order.
     */
    this.rules = { // heheh, this rules!
        
        /**
         * Trims extra space and slashes, standardizes hash usage
         * "http://blah.com#  //  an/ajax/url  //  " ->
         * "http://blah.com#/an/ajax/url"
         */
        normalize: {
            pattern: /^([^#]*)#?(?:\s|%20)*\/*(?:\s|%20)*(.*?)(?:\s|%20)*\/*(?:\s|%20)*$/,
            rewrite: "$1#/$2"
        }
    };
    
    /**
     * Processes the given URL through all the rewrite rules.
     * @param url {String} The URL to rewrite
     * @return {String} The rewritten URL
     */
    this.x = function (url) {
        var reUrl = url;
        if (typeof reUrl == "string" && this.rules) {
            for (var ruleName in this.rules) {
                var rule = this.rules[ruleName];
                if (rule.pattern && rule.pattern.test(reUrl)) {
                    if (rule.rewrite) {
                        reUrl = reUrl.replace(rule.pattern, rule.rewrite);
                    }					
                } 
            }
        }
        return reUrl;
    };
};
